package com.gxa.employment.config;

import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.filter.ThresholdFilter;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.encoder.Encoder;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
import ch.qos.logback.core.util.FileSize;

//@Configuration
public class LogbackConfig {

    private static final String LOG_HOME = "e:/log";
    private static final String LOG_PATTERN = "%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n";

    @PostConstruct
    public void init() {
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

        // 配置通用日志格式
        PatternLayoutEncoder encoder = new PatternLayoutEncoder();
        encoder.setContext(context);
        encoder.setPattern(LOG_PATTERN);
        encoder.start();

        // 控制台输出 Appender
        ConsoleAppender<Object> consoleAppender = new ConsoleAppender<>();
        consoleAppender.setContext(context);
        consoleAppender.setName("CONSOLE");
        consoleAppender.setEncoder((Encoder) encoder);
        consoleAppender.start();

        // 操作日志 Appender（按天滚动）
        RollingFileAppender<Object> operationFileAppender = createRollingFileAppender(context, "OPERATION_FILE",
                LOG_HOME + "/operation/operation.log",
                LOG_HOME + "/operation/%d{yyyy-MM-dd}.log",
                encoder, Level.INFO);

        // 异常日志 Appender（仅记录 ERROR 级别）
        RollingFileAppender<Object> errorFileAppender = createRollingFileAppender(context, "ERROR_FILE",
                LOG_HOME + "/error/error.log",
                LOG_HOME + "/error/%d{yyyy-MM-dd}.log",
                encoder, Level.ERROR);

        // Druid 超时状态日志 Appender
        RollingFileAppender<Object> druidFileAppender = createRollingFileAppender(context, "DRUID_FILE",
                LOG_HOME + "/druid/druid.log",
                LOG_HOME + "/druid/%d{yyyy-MM-dd}.log",
                encoder, Level.DEBUG);

        // 配置 Spring 框架日志级别
        Logger springLogger = context.getLogger("com.gxa.boot");
        springLogger.setLevel(Level.ERROR);
        springLogger.setAdditive(false); // 设置为 false，避免日志向上级传递
        springLogger.addAppender((Appender) errorFileAppender);
//        springLogger.addAppender((Appender) consoleAppender);

        // 业务包的操作日志    不能打印
        Logger aspectLogger = context.getLogger("com.gxa.boot.aspect");
        aspectLogger.setLevel(Level.INFO);
        springLogger.setAdditive(false); // 设置为 false，避免日志向上级传递
        aspectLogger.addAppender((Appender) operationFileAppender);

        // Mapper 包的操作日志
        Logger druidLogger = context.getLogger("com.alibaba.druid.filter.stat.StatFilter");
        druidLogger.setLevel(Level.DEBUG);
        druidLogger.setAdditive(false);
        druidLogger.addAppender((Appender) druidFileAppender);

        // 根日志配置
        Logger rootLogger = context.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
        rootLogger.setLevel(Level.INFO);
        //默认就会有一个根日志控制台打印，所以不用添加   或者全部删除后添加(主要是之前传递的，没有使用false)
//        rootLogger.detachAndStopAllAppenders(); // 移除所有现有 Appender
//        rootLogger.addAppender((Appender) consoleAppender);
    }

    private RollingFileAppender<Object> createRollingFileAppender(LoggerContext context, String appenderName,
                                                                  String currentLogFile, String fileNamePattern,
                                                                  PatternLayoutEncoder encoder, Level level) {
        RollingFileAppender<Object> appender = new RollingFileAppender<>();
        appender.setContext(context);
        appender.setName(appenderName);
        appender.setFile(currentLogFile);

        TimeBasedRollingPolicy<Object> rollingPolicy = new TimeBasedRollingPolicy<>();
        rollingPolicy.setContext(context);
        rollingPolicy.setFileNamePattern(fileNamePattern);
        rollingPolicy.setMaxHistory(30);
        rollingPolicy.setParent(appender);
        rollingPolicy.start();

        SizeBasedTriggeringPolicy<Object> triggeringPolicy = new SizeBasedTriggeringPolicy<>();
        triggeringPolicy.setMaxFileSize(new FileSize(10485760));
        triggeringPolicy.start();

        appender.setRollingPolicy(rollingPolicy);
        appender.setTriggeringPolicy(triggeringPolicy);
        appender.setEncoder((Encoder) encoder);
        appender.start();

        ThresholdFilter filter = new ThresholdFilter();
        filter.setLevel(level.toString());
        filter.start();
        appender.addFilter((Filter) filter);

        return appender;
    }
}